package xyz.ibenben.zhongdian.system.service.sys.impl;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;

import tk.mybatis.mapper.entity.Example;
import xyz.ibenben.zhongdian.common.annotation.SystemServiceLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.dao.sys.SysRoleDao;
import xyz.ibenben.zhongdian.system.entity.sys.SysRole;
import xyz.ibenben.zhongdian.system.mapper.sys.SysRoleMapper;
import xyz.ibenben.zhongdian.system.service.impl.ServiceImpl;
import xyz.ibenben.zhongdian.system.service.sys.*;

/**
 * 系统角色服务实现类
 * 系统级角色管理所使用的，是权限系统中的一部分
 * 提供了一些基本的服务，如查询角色列表、根据角色描述查找是否重复等方法。
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRole> implements SysRoleService{
	private final SysRoleMapper sysRoleMapper;
	private final SysRoleDao sysRoleDao;
	private final SysRoleResourcesService sysRoleResourcesService;

	@Autowired
	public SysRoleServiceImpl(SysRoleMapper sysRoleMapper, SysRoleDao sysRoleDao, SysRoleResourcesService sysRoleResourcesService) {
		this.sysRoleMapper = sysRoleMapper;
		this.sysRoleDao = sysRoleDao;
		this.sysRoleResourcesService = sysRoleResourcesService;
	}

	/**
	 * queryRoleListWithSelected角色记录
	 * @param uid 参数
	 * @return 返回值
	 */
	@Override
	@SystemServiceLog(description = "queryRoleListWithSelected角色记录")
	public List<SysRole> queryRoleListWithSelected(Long uid) {
		return sysRoleMapper.queryRoleListWithSelected(uid);
	}

	/**
	 * delete角色记录
	 * @param key 参数
	 * @param request 参数
	 * @return 返回值
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
	@SystemServiceLog(description = "delete角色记录")
	public int delete(Object key, HttpServletRequest request) {
		//删除角色资源
		int result = 0;
		int resultRR = sysRoleResourcesService.deleteByRoleId(key);
		//删除角色
		SysRole entity = this.selectByKey(key);
		entity.setDelFlag(0);
		entity.setDelId((Long)request.getSession().getAttribute(Constants.SESSIONID));
		entity.setDelTime(new Date());
		int resultR = sysRoleDao.updateByPrimaryKey(entity);
		if(resultRR != 0 && resultR != 0){
			result = resultR;
		}
		return result;
	}

	/**
	 * selectByRoleDesc角色记录
	 * @param roledesc 参数
	 * @return 返回值
	 */
	@Override
	@SystemServiceLog(description = "selectByRoleDesc角色记录")
	public SysRole selectByRoleDesc(String roledesc) {
		SysRole role = null;
		Example example = new Example(SysRole.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("roleDesc",roledesc);
		List<SysRole> roleList = sysRoleDao.selectByExample(example);
		if(!roleList.isEmpty()){
			role = roleList.get(0);
		}
		return role;
	}

}
